//
//  NetworkListener.m
//  Runner
//
//  Created by Willy Liu on 2020/12/16.
//

#import <Foundation/Foundation.h>
#import "NetworkListener.h"
#import "Reachability.h"
#import "callback/NetworkChangeCallback.h"
@interface NetworkListener ()
@property(strong,nonatomic)id networkChangeCallback;//网络状态改变之后的回调
@property (nonatomic) Reachability *internetReachability;
@end

@implementation NetworkListener

- (id)init {
    //调用父类方法,实例一个本类,涉及runtime,防止冲突,可以在构造方法里初始化一些数据等
    self = [super init];
    if (self) {
        // 监测网络情况
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(reachabilityChanged:)
                                                     name: kReachabilityChangedNotification
                                                   object: nil];
        self.internetReachability = [Reachability reachabilityForInternetConnection];
        [self.internetReachability startNotifier];//开启网络状态的监听
    }
    return self;
}

//直接获取当前网络状态
- (void)currentNetworkStateIsAvailable{
    [self doNetworkStateByReachability:self.internetReachability];
}

//网络环境改变回调函数
- (void)reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    [self doNetworkStateByReachability:curReach];
}

//获取网络状态并调用回调
-(void) doNetworkStateByReachability:(Reachability*) curReach{
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
        switch (status){
            case NotReachable:
                NSLog(@"====当前网络状态不可达=======");
                if(_networkChangeCallback!=nil&&[_networkChangeCallback conformsToProtocol:@protocol(NetworkChangeCallback)])
                    [_networkChangeCallback networkStateChangeCallback:NO];
                break;
            case ReachableViaWiFi:
                NSLog(@"====当前网络状态为Wifi=======");
                if(_networkChangeCallback!=nil&&[_networkChangeCallback conformsToProtocol:@protocol(NetworkChangeCallback)])
                    [_networkChangeCallback networkStateChangeCallback:YES];
                break;
            case ReachableViaWWAN:
                NSLog(@"====当前网络状态为WWAN=======");
                if(_networkChangeCallback!=nil&&[_networkChangeCallback conformsToProtocol:@protocol(NetworkChangeCallback)])
                    [_networkChangeCallback networkStateChangeCallback:YES];
                break;
        }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}

//设置网络状态改变之后要调用的回调函数
-(void)setNetChangeCallback:(id) networkChangeCallback{
    _networkChangeCallback=networkChangeCallback;
}

@end
